package com.YCH.behavior.service.impl;

import com.YCH.behavior.service.AppLikesBehaviorService;
import com.YCH.model.behavior.dtos.LikesBehaviorDto;
import com.YCH.model.behavior.pojos.TbLikesBehavior;
import com.YCH.model.common.dtos.ResponseResult;
import com.YCH.model.common.enums.AppHttpCodeEnum;
import com.YCH.model.mappers.app.TbLikesBehaviorMapper;
import com.YCH.model.user.pojos.TbUser;
import com.YCH.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
@Service
@SuppressWarnings("all")
public class AppLikesBehaviorServiceImpl implements AppLikesBehaviorService {

    @Autowired
    private TbLikesBehaviorMapper apLikesBehaviorMapper;

    @Override
    public ResponseResult saveLikesBehavior(LikesBehaviorDto dto){
        // 1.校验参数
        TbUser user = AppThreadLocalUtils.getUser();
        // 用户和用户id不能同时为空
        if (user == null && dto.getUserId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        Long userId = null;
        if (user != null) {
            userId = user.getId();
        }
        if(dto.getUserId()!=null){
            userId = dto.getUserId();
        }
        if(dto.getArticleId() == null && dto.getCommentId() ==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"文章和评论id不能同时为空!");
        }
        // 查询该用户是否已经取消点赞,3种情况，前两种在sql语句中处理，第三种情况返回空
        TbLikesBehavior tbLikesBehavior = null;
        // 情况一：articleId 不为空，commentId 为空
        // 情况二：commentId 不为空，articleId 为空
        // 情况三：commentId 不为空，articleId 不为空
        if(dto.getArticleId() !=null && dto.getCommentId() != null){
            ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"文章和评论id不能同时出现");
        }else {
            tbLikesBehavior = apLikesBehaviorMapper.selectCancleLike(userId, dto.getArticleId(),dto.getCommentId(),dto.getCommentReplayId(), dto.getType());
        }
        // 操作为零就是点赞
        if(dto.getOperation() == 0 && tbLikesBehavior == null){
            // 当数据库中没有查到该用户取消点赞，且用户操作是点赞，就插入点赞
            TbLikesBehavior alb = new TbLikesBehavior();
            alb.setUserId(userId);
            alb.setCreatTime(new Date());
            alb.setArticleId(dto.getArticleId());
            alb.setCommentId(dto.getCommentId());
            alb.setType(dto.getType());
            alb.setOperation(dto.getOperation());
            return ResponseResult.okResult(apLikesBehaviorMapper.insert(alb));
        }else {// 否则就是取消点赞/恢复点赞
            TbLikesBehavior alb = new TbLikesBehavior();
            alb.setUserId(userId);
            alb.setArticleId(dto.getArticleId());
            alb.setCommentId(dto.getCommentId());
            alb.setOperation(dto.getOperation());
            return ResponseResult.okResult(apLikesBehaviorMapper.updata(alb));
        }
    }
}
